<template>
	<view>
		<template v-if="isshow">
	<view class="formModel">
		<view class="cu-form-group">
			<view class="title">运输车辆车牌号</view>
			<picker @change="ArrChange" :value="carIndex" :range="carShow">
				<view class="picker">
					{{carArr[carIndex].license_plate}}
				</view>
			</picker>
		</view>
		<view class="cu-form-group" >
			<view class="title">到达养殖场日期</view>
			<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
				<view class="picker">{{date}}</view>
			</picker>
		</view>
		<view class="cu-form-group">
			<view class="title">到达养殖场时间</view>
			<picker mode="time" :value="time" start="09:01" end="21:01" @change="bindTimeChange">
				<view class="picker">{{time==""?"请选择时间":time}}</view>
			</picker>
		</view>
		<view class="cu-form-group">
			<view class="title">运输目的地</view>
			<input v-model="transportation_destination" placeholder="请输入运输目的地" focus='true' name="input"></input>
		</view>
		<view class="cu-form-group">
			<view class="title">处理批次号</view>
			<input type="number" v-model="pool_number" placeholder="请输入批次号" focus='true' name="input"></input>
		</view>
		<view class="cu-form-group">
			<view class="title">沼液池编号</view>
			<picker @change="PickerChange" :value="poolIndex" :range="pool">
				<view class="picker">
					{{pool[poolIndex]}}
				</view>
			</picker>
		</view>
		
		<view class="cu-form-group">
			<view class="title">运输重量</view>
			<input type="number" v-model="transportation_weight" placeholder="请输入运输重量" focus='true' name="input"></input>
		<text style="font-size:30rpx;">KG</text>
		</view>
		<view class="cu-form-group">
			<view class="title">司机名</view>
			<input v-model="registrant_name" placeholder="请输入司机名字" focus='true' name="input"></input>
		</view>
		<view class="cu-form-group">
			<view class="title">联系方式</view>
			<input type="number" maxlength="11" v-model="registrant_phone" placeholder="请输入电话号码" focus='true' name="input"></input>
		</view>
		<view class="cu-form-group">
			<view class="title">身份证号</view>
			<input maxlength="18" v-model="id_card_picture" placeholder="请输入司机身份证号" focus='true' name="input"></input>
		</view>
		<view class="imageUp">
			<view class="cu-bar bg-white" style="justify-content: space-between;margin-top:0rpx">
				<view class="action">
					司机身份证图片上传
				</view>
				<view class="action" style="font-size: 30rpx;">
					{{imgList.length}}/1
				</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
					 <image :src="imgList[index]" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="ChooseImage" v-if="imgList.length<1">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
		</view>
		</view>
		</template>
	<template v-else>
		
	</template>
	</view>
</template>

<script>
	function getDate(type) {
		const date = new Date();
	
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();
	
		if (type === 'start') {
			year = year - 60;
		} else if (type === 'end') {
			year = year + 2;
		}
		month = month > 9 ? month : '0' + month;;
		day = day > 9 ? day : '0' + day;
	
		return `${year}-${month}-${day}`;
	}
	export default {
		data() {
			return {
				date: getDate({
					format: true
				}),
				startDate:getDate('start'),
				endDate:getDate('end'),
				time: '',//ui库
				
				isshow:false,
				imgList: [],
				num:0,
				licensePlate:"",
				hasLocation: false,
				location: {},
				locationAddress: '',
				carArr:[],//车辆信息
				carIndex:0,//车辆下标
				carShow:[],//车辆显示
				//表单提交数据
				car_number:'',//运输车辆车牌号
				car_arrive_time:'',//车辆到达养殖场时间
				pool_number:'',//处理批次号
				pool_id:'',//沼液池编号（下拉框）
				pool:["请选择"],//沼液池编号集合下拉显示
				PoolArr:["请选择"],//沼液池编号集合
				poolIndex:0,//选中下标
				transportation_destination:'',//运输目的地
				transportation_weight:'',//运输重量
				registrant_name:'',//登记人
				registrant_phone:'',//联系方式
				id_card_picture:'',//身份证号码
				imagePaths:[],//身份证图片路径
			};
		},
		onPullDownRefresh() {
			uni.stopPullDownRefresh();
		},
		onNavigationBarButtonTap(){
			//提交数据
			this.CarInfoAdd()
		},
		beforeCreate() {
			uni.startPullDownRefresh();
		},
		onReady() {
			// console.log(this.$u.config.v);
			//获取养殖场的沼液池
			this.getPoolId()
			//获取签约车辆
			this.getFarmerCar();
		},
		methods:{
			bindDateChange: function(e) {
				this.date = e.detail.value
				console.log(this.date)
			},
			bindTimeChange: function(e) {
				this.time = e.detail.value
				console.log(this.time)
			},
			//提交数据
			CarInfoAdd(){
				let poolId = this.pool[this.poolIndex];
				if(poolId==="请选择"){
					uni.showToast({
						title:"请选择沼液池",
						icon:"none"
					});
					return;
				}
				// if(this.imgList.length>0){
				// 	for(let i=0;i<this.imgList.length;i++){
				// 		this.imageUpload(this.imgList[i]);
				// 	}
				// }
				uni.showLoading();
				let carNum  = this.carArr[this.carIndex].license_plate
				// 460030197809200927
				// let time = this.timeData.year+'-'+this.timeData.month+'-'+this.timeData.day+' '+this.timeData.hour+':'+this.timeData.minute;
				let time = this.date +" "+ this.time
				uni.request({
					url:this.confige.webUrl+"/filing/addCarInfo",
					data:{					car_number:carNum,
					car_arrive_time:time,
					transportation_destination:this.transportation_destination,
					pool_number:this.pool_number,
					pool_id:poolId,
					transportation_weight:this.transportation_weight,
					registrant_name:this.registrant_name,
					registrant_phone:this.registrant_phone,
					id_card_picture:this.id_card_picture,
					id_card_picture_url:this.imagePaths[this.imagePaths.length-1],
					transportation_status:"运输中"
					},
					header:{
						'X-Token':this.User.token
					},
					method:"POST",
					success: (res) => {
						console.log(res);
						uni.hideLoading();
						console.log(this.imagePaths)
						if(res.data.code==504 || res.data.code==400){
							uni.showToast({
								title:res.data.message,
								icon:"none"
							});
							this.deleteServerImg()
						}
						else if(res.data.code==200){
							uni.showModal({
								title:"提示",
								showCancel:false,
								content:"您已成功进行车辆运输备案",
							    success:(res)=> {
									if (res.confirm) {
									uni.redirectTo({
										url:"./carNumList"
									})
									} 
								}
							});
						}
					}
				})
			},
			//图片上传
			imageUpload(FilePaths){
				uni.showLoading({
					title:"图片上传中"
				});
				 uni.uploadFile({
				            url:this.confige.webUrl+"/filing/vehiclesImg",
				            filePath:FilePaths,
				            name:'file',
				            formData:{
				                'token':this.User.token
				            },
				            success: (uploadFileRes) => {
								uni.hideLoading();
								let img = JSON.parse(uploadFileRes.data)
								this.imagePaths.push(img.url);
								 console.log(this.imagePaths)
				            },
							fail: (err) => {
								console.log(err)
							}
				        });
			},
			//删除服务器的图片
			deleteServerImg(){
				uni.request({
					url:this.confige.webUrl+"/delePicture",
					data:{
						picture:this.imagePaths[0]
					},
					header:{
						'X-Token':this.User.token
					},
					success: (res) => {
						console.log(res);
						this.imagePaths = []
					}
				})
			},
			//车牌号选中
			ArrChange(e){
				this.carIndex = e.detail.value;
			},
			//沼液池编号下拉值选中
			PickerChange(e) {
				this.poolIndex = e.detail.value;
				// console.log(e.detail.value)
			},
			//获取签约车辆
			getFarmerCar(){
				uni.request({
					url:this.confige.webUrl+"/filing/selectCarInfo",
					data:{
					},
					header:{
						'X-Token':this.User.token
					},
					success: (res) => {
						// console.log(res)
						let list = res.data.result;
						this.carArr = res.data.result
						let arr = [];
						for(let i=0;i<list.length;i++){
							arr.push(
								list[i].license_plate
							)
						}
						this.carShow = arr;
						
						this.isshow = true;
						setTimeout(()=>{
							uni.stopPullDownRefresh();
						},500)
					}
				})
			},
			//获取养殖场的沼液池
			getPoolId(){
				// console.log(this.User.userInfo.farm_id)
				uni.request({
					url:this.confige.webUrl+"/filing/selectPoolId",
					data:{
						farm_id:this.User.userInfo.farm_id
					},
					header:{
						'X-Token':this.User.token
					},
					success: (res) => {
						// console.log(res)
						let list = res.data.result;
						if(!list){
							let o = ["暂无绑定沼液池"];
							this.pool = o;
							return;
						}
						let arr = [];
						for(let i=0;i<list.length;i++){
							arr.push(
							list[i].pool_id	
							)
						}
						this.pool.push(...arr);
						// console.log(this.pool);
						
					}
				})
			},
			ChooseImage(){
				uni.chooseImage({
					count:1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths)
						} else {
							this.imgList = res.tempFilePaths
							this.imageUpload(this.imgList[0]);
						}
					}
				});
			},
			//预览图片
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			//取消上传
			DelImg(e) {
				uni.showModal({
					title: '提示',
					content: '确定要取消该照片的上传吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			upload(){
				this.num++;
				if(this.num == 1){
				uni.showModal({
					title:'提示',
					content:'图片已上传，请等待审核',
					showCancel:false
				})
				}
				else if(this.num >1){
					uni.showToast({
						title:"请不要重复提交",
						icon:"none"
					})
				}
			}
		}
	}
</script>

<style lang="less" scoped>
	@import "../../../common/global.less";
	@import "../../../common/main.css";
	@import "../../../common/colorui/icon.css";
	.timeInput{
		// border-bottom: 1rpx solid #bcbcbc;
		color: #000000;
		text-align: center;
		width: 100rpx;
		height: 10rpx;
		// !important
	}
	.textInput{
		font-size: 32rpx;
		padding: 0rpx 10rpx;
	}
	.formModel{
	background-color:@backcolorthree;
	border-bottom:2rpx solid #eaeaea;
	.cu-form-group {
	.title {min-width: calc(4em + 15px);}		
	}
	}
	.bottomButModel{ 
		width: 100%;
		>button{ 
		 float:right;
		 margin-top: 20rpx;
		 margin-right: 20rpx;
		 font-size: 30rpx;
		 width: 150rpx;
		 
		 border-radius: 50rpx;
		 border: 1rpx solid #000000;
		 }
	}
	.imageUp{ 
		
	border-top: 2rpx solid #ececec;
	}
	.centerFlexLayout{  
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	}
	
</style>
